package com.heima.search.listener;


import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.pojos.SearchArticleVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RequiredArgsConstructor
public class SyncArticleListener {

    private final RestHighLevelClient restHighLevelClient;


    /**
     * 接受消息，向索引库app_info_article新增文档
     *
     * @param message
     */
    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void addDocument(String message) {
        log.info("新增文档,{}",message);
        if (StringUtils.isNotBlank(message)) {
            SearchArticleVo vo = JSON.parseObject(message, SearchArticleVo.class);
            // 1、准备request
            IndexRequest indexRequest = new IndexRequest("app_info_article");
            // 2、准备参数
            // 设置文档的ID
            indexRequest.id(vo.getId().toString());
            // 设置文档的源数据
            indexRequest.source(message, XContentType.JSON);
            // 执行索引操作，将文档添加到索引中
            try {
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("sync es error={}", e);
            }

        }
    }
}
